import React, { useRef, useEffect } from 'react'
import * as echars from 'echarts'

const axisOption = {
  //图例文字颜色
  textstyle: {
    color: '#333'
  },
  // 提示框
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category', //类目轴
    data: [],
    axisLine: {
      linestyle: {
        color: '#17b3a3'
      },
      axisLabel: {
        interval: 0,
        color: '#333'
      }
    }
  },
  yAxis: [
    {
      type: 'value',
      axisLine: {
        linestyle: {
          color: '#17b3a3'
        }
      },
      color: ['#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb980', '#d87a80', '#8d98b3']
    }
  ]
}

const normalOption = {
  tooltip: {
    trigger: 'item'
  },
  color: ['#Of78f4', '#dd536b', '#9462e5', '#a6a6a6', '#e1bb22', '#39c362', '#3ed1cf'],
  series: []
}

const Echarts = ({style, chartData, isAxisChart = true}) => {
  const echartRef = useRef()
  let echartsObj = useRef(null)
  useEffect(() => {
    initEchart()
  }, [chartData])

  const initEchart = () => {
    echartsObj.current = echars.init(echartRef.current)
    if (isAxisChart) {
      // 设置x轴
      axisOption.xAxis.data = chartData.xData
      axisOption.series = chartData.series
    } else {
      normalOption.series = chartData.series
    }
    echartsObj.current.setOption(isAxisChart ? axisOption : normalOption)
  }
  return (
    <>
      <div style={style} ref={echartRef}></div>
    </>
  )
}

export default Echarts
